package cn.new7as.cas5s.tool.util;


import android.annotation.SuppressLint
import android.content.Context
import android.hardware.input.InputManager
import android.os.Build
import android.os.SystemClock
import android.provider.Settings
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import android.util.Log
import android.view.InputDevice
import cn.new7as.cas5s.tool.phut.funs.Bjhxka
import cn.new7as.cas5s.tool.phut.funs.Genvciad
import cn.new7as.cas5s.tool.phut.funs.Hardcxkdasd
import cn.new7as.cas5s.tool.phut.funs.JshkxzaD
import cn.new7as.cas5s.tool.phut.funs.PhoneData
import cn.new7as.cas5s.tool.phut.funs.Stoxjdada

import cn.new7as.cas5s.ui.easy.AppConsant
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.PhoneUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone



class PhoneDataUtil {
    companion object {
        private var mSingleton: PhoneDataUtil? = null
            get() {
                if (field == null) {
                    field = PhoneDataUtil()
                }
                return field
            }

        @Synchronized
        fun getInstance(): PhoneDataUtil {
            return mSingleton!!
        }
    }


    suspend fun phonedata(): PhoneData {


        return PhoneData().apply {
            zxaRbdeBybxi = ArrayList<java.lang.Exception>()


            try {
                tnkEyzfyCbx = getBatteryStatus()

            } catch (e: Exception) {
                zxaRbdeBybxi!!.add(e)
            }
            try {
                qqsukQuwSoxhc = getGenerateData()

            } catch (e: Exception) {
                zxaRbdeBybxi!!.add(e)
            }
            try {
                oxvbaTnqQceSseg = getHardware()

            } catch (e: Exception) {
                zxaRbdeBybxi!!.add(e)
            }
            try {
                kpcLaqiHcqVwmKsj = getOtherData()

            } catch (e: Exception) {
                zxaRbdeBybxi!!.add(e)
            }
            try {
                ciqzEvfmRloo = getStorage()

            } catch (e: Exception) {
                zxaRbdeBybxi!!.add(e)
            }
        }
    }


}



/**
 * Battery
 */
fun getBatteryStatus(): Bjhxka? {
    if (SPUtils.getInstance().getString("batterData").isEmpty()) {
        var batteryData  = Gson().toJson(SPUtils.getInstance().getString("batterData"))
        return batteryData as Bjhxka
    } else {
        return Bjhxka(
            jpgsaFbsHeuXiev = false,
            jobBstRchspYrnAlsb = 0,
            jdzdQhlcgOsbfdQtws = false,
            qwkmSemydOwclXrifoDcmst = false,
            akpxoXhtqgEmzKct = null,
            ljdvSnrsrNqkypRpmaUmfdt = null,
            sarAegpUoszuMwcpl = null,
            eazxRtiYvfqeQka = null,
            lrteIzxnWxuyJkivu = null,
        )
    }


}

@SuppressLint("MissingPermission")
suspend fun getGenerateData(): Genvciad = withContext(Dispatchers.IO) {
    val adid = getADIDTimeout()
    val generalData = Genvciad(
        pnywxDpzBirw = PhoneDataFunUtils.getAndroidId(),
        qyxenBlmCiksGdkwt = adid,
        bikvEoigCyxsvWjfdnPyv = PhoneDataFunUtils.getIMEI(),
        nfabSlneZqm = PhoneDataFunUtils.getIMSI(),
        vlzoAadAsh = LanguageUtils.getSystemLanguage()?.displayLanguage,
        rzbDmxnaDvjRbrgh = LanguageUtils.getAppliedLanguage()?.displayLanguage,
        ubiqgCtsTcpvZtv = Locale.getDefault().isO3Country,
        fquicCgzhqWtfRaaytBck = Locale.getDefault().isO3Language,
        wmdShibqLqye = DeviceUtils.getMacAddress(),
        leyCmvkFamdy = NetworkUtils.getNetworkOperatorName(),
        plxxxCycuEvydUetLtuks = NetworkUtils.getNetworkType().name,
        vxkMhbGchxVgpil = PhoneUtils.getPhoneType().toString(),
        avsSekaOryGofmu = TimeZone.getDefault().id,
        ucivEipdkChiZtuGphkv = DeviceUtils.getUniqueDeviceId()
    )
    generalData
}

//    /**
//     * google id - adjust
//     */
val defaultGoogleAdId = "00000000-0000-0000-0000-000000000000"

suspend fun getADIDTimeout(): String? {
    return try {
        withTimeoutOrNull(10 * 1000) {
            getADID()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

/**
 * get google ads ID
 */
suspend fun getADID(): String? = suspendCancellableCoroutine { coroutine ->
    //
    GlobalScope.launch(Dispatchers.IO) {
        try {
            val advertisingIdInfo =
                AdvertisingIdClient.getAdvertisingIdInfo(AppConsant.getsInstance())
            var id = advertisingIdInfo.id
            if (id != null && id != defaultGoogleAdId) {
                //serve id
                coroutine.resume(id, null)
            } else {
                coroutine.resume(null, null)
            }
            Log.i("getGoogleAdId", "Facebook googleAdId $id")
        } catch (e: Exception) {
            coroutine.resume(null, null)
        }
    }
}

/**
 * Hardware
 */
@SuppressLint("MissingPermission")
fun getHardware(): Hardcxkdasd {
    val abis = DeviceUtils.getABIs()
    return Hardcxkdasd(
        clyWeydGzoPzob = if (abis.isNullOrEmpty()) null else abis.toList().toString(),

        rhqtVocEirnWag = Build.SUPPORTED_ABIS.toList().toString(),
        owljhRqwslOwlgYzy = Build.DEVICE,

        bqgrKrbcJuj = Build.MANUFACTURER,
        bktpeXtdXgu = Build.MODEL,
        puiebSqaiyHzpawBor = PhoneDataFunUtils.getPhysicsScreenSize().toString(),
        whzEssfGbbBptDziz = Build.getRadioVersion(),
        vrhkhKyabaTkvfKkob = Build.VERSION.RELEASE,
        ptckZlnSaxpUdiuh = ScreenUtils.getScreenDensity().toString(),
        tzfbMtvWqwngFxeDrh = ScreenUtils.getScreenDensityDpi().toString(),
        uklmPvstxFew = ScreenUtils.getScreenHeight().toString(),
        ggeocEdzKpzliYgze = ScreenUtils.getScreenWidth().toString(),
        ckjdHczAwzma = PhoneDataFunUtils.getSDKVersionName(),
        bikvEoigCyxsvWjfdnPyv = PhoneDataFunUtils.getIMEI()
    )
}

fun getOtherData(): JshkxzaD {
    val dbmStr = StringBuilder()
    var signalStrength: SignalStrength? = null
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        signalStrength = (AppConsant.getsInstance()
            .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).signalStrength
    }
    if (signalStrength != null) {
        val asu = signalStrength.gsmSignalStrength
        dbmStr.append(-113 + 2 * asu)
    }

    // keyboard
    var keyboardName: String? = null
    val inputManager =
        AppConsant.getsInstance().getSystemService(Context.INPUT_SERVICE) as InputManager?
    if (inputManager != null) {
        val inputDeviceIds: IntArray = inputManager.getInputDeviceIds()
        val list = arrayListOf<String>()
        for (deviceId in inputDeviceIds) {
            val inputDevice: InputDevice = inputManager.getInputDevice(deviceId)!!
            val sources: Int = inputDevice.getSources()

            // iskeyboard
            if (sources and InputDevice.SOURCE_KEYBOARD == InputDevice.SOURCE_KEYBOARD) {
                list.add(inputDevice.name)
                Log.d("KeyboardInfo", "Keyboard Name: " + inputDevice.name);
            }
        }
        keyboardName = list.toString()
    }
    var mockLocationEnabled  = isMockLocationEnabled(AppConsant.getsInstance())
    return JshkxzaD(
        yurfuZhniMxavf = dbmStr?.toString(),
        sbccqOkoiLeyjRrn = false,
        rstjiLjcTweWsrtGlw = mockLocationEnabled,
        byjXslpKno = keyboardName!!,
        dhaOokItkir = (System.currentTimeMillis() - SystemClock.elapsedRealtime()).simple(),
        mjekUjfVopiTomLfmoz = hasRootPrivilege(),
        heocLhkYoqyi = DeviceUtils.isEmulator()
    )
}

fun isMockLocationEnabled(context: Context): Boolean {
    if (Settings.Secure.getString(context.contentResolver, Settings.Secure.LOCATION_MODE)!=null)
    return Settings.Secure.getString(context.contentResolver, Settings.Secure.LOCATION_MODE)
        .equals("0")
    else return false
}

/**
 *
 */
fun Long.simple(): String {
    val simpleDateFormat = SimpleDateFormat("yyyy/M/dd HH:mm:ss", Locale.getDefault())
    return simpleDateFormat.format(Date(this))
}



private val rootRelatedDirs = arrayOf(
    "/su",
    "/su/bin/su",
    "/sbin/su",
    "/data/local/xbin/su",
    "/data/local/bin/su",
    "/data/local/su",
    "/system/xbin/su",
    "/system/bin/su",
    "/system/sd/xbin/su",
    "/system/bin/failsafe/su",
    "/system/bin/cufsdosck",
    "/system/xbin/cufsdosck",
    "/system/bin/cufsmgr",
    "/system/xbin/cufsmgr",
    "/system/bin/cufaevdd",
    "/system/xbin/cufaevdd",
    "/system/bin/conbb",
    "/system/xbin/conbb"
)

fun hasRootPrivilege(): Boolean {
    var hasRootDir = false
    var rootDirs: Array<String>
    val dirCount = rootRelatedDirs.also { rootDirs = it }.size
    for (i in 0 until dirCount) {
        val dir = rootDirs[i]
        if (File(dir).exists()) {
            hasRootDir = true
            break
        }
    }
    return Build.TAGS != null && Build.TAGS.contains("test-keys") || hasRootDir
}


fun getStorage(): Stoxjdada {
    return Stoxjdada(
        momqRbzyZpuoAhcJyykf = PhoneDataFunUtils.getInternalSize().toString(),
        zdzqrTotXjrngAxabl = PhoneDataFunUtils.getAvailableInternalSize().toString(),
        xpoWuaswXmeNapsj = PhoneDataFunUtils.getSDCardTotalSize().toString(),
        ohqXjcLibgr = PhoneDataFunUtils.getSDCardAvailSize().toString(),
        ehfAxakGxiad = PhoneDataFunUtils.getRAMTotalMemorySize(AppConsant.getsInstance()).toString(),
        nrmjzAnjkKuxzqFvmbf = PhoneDataFunUtils.getRAMAvaialbeMemorySize(AppConsant.getsInstance())
            .toString()
    )


}
